package com.example.helloworldspringboot.controller;

import com.example.helloworldspringboot.entity.Category;
import com.example.helloworldspringboot.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @RequestMapping("/category")
    public String getAllCategories(Model model){
           List<Category> all =  categoryService.queryAllCategory();
           model.addAttribute("username","admin");
           model.addAttribute("data",all);
           return "category";
    }

    @RequestMapping("/category/addCategory")
    public String addCategory(@RequestParam String name){
        Category category=new Category();
        category.setName(name);
        category.setStatus("0");
        if(categoryService.addCategory(category)==1){
            return "redirect:/category";
        }else{
            return "redirect:/category";
        }
    }

    @RequestMapping("/category/deleteCategory")
    public String deleteCategory(@RequestParam String id){
        Category category=new Category();
        category.setId(Integer.parseInt(id));
        if(categoryService.deleteCategory(category)==1){
            return "redirect:/category";
        }else{
            return "redirect:/category";
        }
    }

    @RequestMapping("/category/updateCategory")
    public String updateCategory(@RequestParam String id,@RequestParam String name){
        Category category=new Category();
        category.setId(Integer.parseInt(id));
        category.setName(name);
        if(categoryService.updateCategory(category)==1){
            return "redirect:/category";
        }else{
            return "redirect:/category";
        }
    }
}
